package cn.slipi.core.handler;

import cn.slipi.core.plugin.IPlugin;
import cn.slipi.core.plugin.IPluginChain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebHandler;
import reactor.core.publisher.Mono;

import java.util.List;

public class CoreWebHandler implements WebHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(CoreWebHandler.class);

    private final List<IPlugin> plugins;

    public CoreWebHandler(final List<IPlugin> plugins) {
        this.plugins = plugins;
    }

    @Override
    public Mono<Void> handle(ServerWebExchange serverWebExchange) {
        return new DefaultPluginChain(plugins).execute(serverWebExchange).doOnError(Throwable::printStackTrace);
    }

    private static class DefaultPluginChain implements IPluginChain {

        private int index;
        private final List<IPlugin> plugins;

        public DefaultPluginChain(List<IPlugin> plugins) {
            this.plugins = plugins;
        }

        @Override
        public Mono<Void> execute(ServerWebExchange exchange) {
            if (index < plugins.size()) {
                IPlugin plugin = plugins.get(index++);
                return plugin.execute(exchange, this);
            } else {
                return Mono.empty();
            }
        }
    }
}
